package cn.itcast.tanhua.server.service;
import cn.itcast.tanhua.common.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName UserService
 * @Description 通过restTemplate连接sso校验token
 * @Author WU
 * @Date 2021/5/28 16:36
 * @Version 1.0
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

//    json转化工具
    private static final ObjectMapper MAPPER=new ObjectMapper();

    /**
    * @Description: 通过访问sso校验token
    * @Param:
    * @return:
    * @Author: Mr.Tan
    * @Date: 2021/5/28
    */
    public User queryUserByToken(String token) {
//        拼接url
        String url=ssoUrl+"/user/"+token;
        try {
//            访问之后，如果token校验通过则会返回user，校验失败则会返回空字符串
            String data = this.restTemplate.getForObject(url, String.class);
            if (StringUtils.isEmpty(data)) {
                return null;
            }
//            校验通过后，将获取到的json数据转为java类
            return MAPPER.readValue(data,User.class);
        } catch (Exception e) {
            log.error("校验token出错，token = " + token, e);
        }
//返回一个null，防止报错
        return null;
    }
}
